package com.atgugu.realtime.function;

import com.atgugu.realtime.common.Constant;
import com.atgugu.realtime.util.JdbcUtil;
import com.atgugu.realtime.util.RedisUtil;
import com.atgugu.realtime.util.ThreadPoolUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/29 14:40
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> {
    
    private ThreadPoolExecutor threadPool;
    
    @Override
    public void open(Configuration parameters) throws Exception {
        threadPool = ThreadPoolUtil.getThreadPool();
        
    }
    
    public abstract void addDim(Jedis jedis, Connection phoenixConn, T input, ResultFuture<T> resultFuture);
    
    @Override
    public void asyncInvoke(T input,
                            ResultFuture<T> resultFuture) throws Exception {
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                Connection phoenixConn = null;
                Jedis jedis = null;
                // reids客户端 Phoenix连接对象 这些必须一个异步请求使用一个单独客户端
                try {
                    jedis = RedisUtil.getRedisClient();
                    phoenixConn = JdbcUtil.getJdbcConnection(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL);
                    // 使用客户端开始具体的查询数据, 补充维度
                    addDim(jedis, phoenixConn, input, resultFuture);
                    
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (jedis != null) {
                        jedis.close();
                    }
                    
                    if (phoenixConn != null) {
                        try {
                            phoenixConn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
                
            }
        });
        
    }
}
